package com.fansl.allround.upms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fansl.allround.common.core.constant.enums.RegionLevelEnum;
import com.fansl.allround.common.core.util.R;
import com.fansl.allround.common.log.annotation.SysLog;
import com.fansl.allround.upms.api.entity.SysRegion;
import com.fansl.allround.upms.helper.RegionHelper;
import com.fansl.allround.upms.service.SysRegionService;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;


/**
 * 区域信息
 *
 * @author code generator
 * @date 2019-08-22 16:08:14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/region")
@Slf4j
public class RegionController {

    private final SysRegionService sysRegionService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 简单分页查询
     *
     * @param page      分页对象
     * @param sysRegion 区域信息
     * @return
     */
    @GetMapping("/page")
    public R<IPage<SysRegion>> getSysRegionPage(Page<SysRegion> page, SysRegion sysRegion) {
        return new R<>(sysRegionService.getSysRegionPage(page, sysRegion));
    }


    /**
     * 通过id查询单条记录
     *
     * @param id
     * @return R
     */
    @GetMapping("/{id}")
    public R<SysRegion> getById(@PathVariable("id") Integer id) {
        return new R<>(sysRegionService.getById(id));
    }

    /**
     * 新增记录
     *
     * @param sysRegion
     * @return R
     */
    @SysLog("新增区域信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('upms_region_add')")
    public R save(@RequestBody SysRegion sysRegion) {
        return new R<>(sysRegionService.save(sysRegion));
    }

    /**
     * 修改记录
     *
     * @param sysRegion
     * @return R
     */
    @SysLog("修改区域信息")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('upms_region_edit')")
    public R update(@RequestBody SysRegion sysRegion) {
        return new R<>(sysRegionService.updateById(sysRegion));
    }

    /**
     * 通过id删除一条记录
     *
     * @param id
     * @return R
     */
    @SysLog("删除区域信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('upms_region_del')")
    public R removeById(@PathVariable Integer id) {
        return new R<>(sysRegionService.removeById(id));
    }

    @SysLog("爬取区域信息")
    @PostMapping("/crawl")
    public R crawlRegionInfo() {
        RegionHelper.executeSpider(RegionLevelEnum.PROVINCE,
                Arrays.asList("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/index.html"),
                true,
                sysRegionService, redisTemplate);
        return new R<>(Boolean.TRUE);
    }

    /**
     * 爬取redis中的区域信息
     *
     * @return
     */
    @SysLog("爬取redis中的区域信息")
    @PostMapping("/crawl/{regionLevel}")
    public R regionCrawlRedis(@PathVariable RegionLevelEnum regionLevel) {
        String redisKey = RegionHelper.PREFIX_REGION_HELP_URL_KEY_IN_REDIS + regionLevel;
        Long size = redisTemplate.opsForSet().size(redisKey);
        if (size == 0) {
            log.warn("当前区域信息在redis中未找到");
            return new R<>(Boolean.TRUE);
        }
        CompletableFuture.runAsync(() -> {
            Cursor<String> cursor = redisTemplate.opsForSet().scan(redisKey, ScanOptions.NONE);
            while (cursor.hasNext()) {
                String pageUrl = cursor.next();
                log.info("爬取区域信息。pageUrl:{}", pageUrl);
                RegionHelper.executeSpider(regionLevel, Arrays.asList(pageUrl),
                        false, sysRegionService, redisTemplate);
            }
        });
        return new R<>(Boolean.TRUE);
    }
}
